<template>
  <div>
    <div style="padding-bottom: 20px;">
        <span style="color: rgba(47,47,47,0.85); font-size: 13px">
          <i class="el-icon-warning-outline"></i>
          精简模式下参数只支持输入框的方式录入
        </span>
    </div>
    <el-tabs v-model="tabsValue" tab-position="left" :stretch="true" @tab-click="handleClick(functions)">
      <el-tab-pane
        v-for="fun in functions"
        :key="fun.id"
        :label="fun.name"
        :name="fun.id"
      >
        <el-row>
          <el-col :span="13">
            <el-form :ref="`form${fun.id}`" :model="form" :rules="rules">
              <el-row>
                <el-table :data="fun.inputs" @ready="handleFormValidate">
                  <el-table-column prop="name" label="参数名称" width="200"></el-table-column>
                  <el-table-column prop="valueType.type" label="输入类型" width="180"></el-table-column>
                  <el-table-column align="center" label="值">
                    <template slot-scope="scope">

                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['int', 'long', 'float', 'double', 'string'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-input v-model="form[scope.row.id]" :placeholder="'请输入' + scope.row.name"/>
                      </el-form-item>

                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['enum'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-select v-model="form[scope.row.id]" class="select-width">
                          <el-option
                            v-for="(item) in scope.row.valueType.elements"
                            :key="item.value"
                            :label="item.text"
                            :value="item.text"
                          />
                        </el-select>
                      </el-form-item>

                      <!-- boolean -->
                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['boolean'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-select v-model="form[scope.row.id]" class="select-width">
                          <el-option :label="scope.row.valueType.trueText" :value="scope.row.valueType.trueValue"/>
                          <el-option :label="scope.row.valueType.falseText" :value="scope.row.valueType.falseValue"/>
                        </el-select>
                      </el-form-item>
                      <!-- boolean -->

                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['date'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-date-picker
                          v-model="form[scope.row.id]"
                          type="datetime"
                          placeholder="选择日期时间"
                          align="right"
                          style="width:100%;"
                          :value-format="scope.row.valueType.format"
                        >
                        </el-date-picker>
                      </el-form-item>

                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['object'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-input v-model="form[scope.row.id]">
                          <el-button
                            slot="append"
                            icon="el-icon-edit-outline"
                            @click="handleInputs(form[scope.row.id],scope.row.id)">
                          </el-button>
                        </el-input>
                      </el-form-item>

                      <el-form-item
                        :prop="scope.row.id"
                        v-if="handleFormShow(scope.row.valueType.type, ['array'])"
                        :rules="handleRules(scope.row)"
                      >
                        <el-select
                          v-model="form[scope.row.id]"
                          class="select-width"
                          multiple
                          filterable
                          allow-create
                          default-first-option
                          placeholder="请选择">
                          <el-option
                            v-for="item in arrayOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>

                    </template>
                  </el-table-column>
                </el-table>
              </el-row>

              <el-row style="margin-top: 20px">
                <div style="float: right">
                  <el-button type="primary" @click="submitForm(fun)">执行</el-button>
                  <el-button @click="reset(fun)">清空</el-button>
                </div>
              </el-row>

            </el-form>

          </el-col>
          <el-col :span="10" style="padding-left: 100px">
            <el-form ref="result" :model="result">
              <template>
                <span>执行结果：</span>
                <p></p>
                <el-input
                  style="margin-top: 20px"
                  v-model="result.data"
                  :autosize="{ minRows: 4 }"
                  type="textarea"
                  readonly/>

              </template>
            </el-form>
          </el-col>

        </el-row>

      </el-tab-pane>
    </el-tabs>

    <!--  Object类型编写框  -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>

      <div>
        <el-form ref="objectData" :model="objectData" label-width="70px">

          <editor
            v-model="objectData.params"
            @init="editorInit"
            lang="json"
            theme="chrome"
            style="height: 350px"
            :options="editorOptions"
          />

        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="margin-top: 40px">
        <el-button type="primary" @click="saveObject">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>


  </div>

</template>

<script>
import Template from '@/views/notify/template'
import Editor from 'vue2-ace-editor'
import {invokedFunction} from '@/api/iot/device'

export default {
  name: 'simple',
  components: {Template, Editor},
  data() {
    return {
      //功能列表
      functions: [],
      tabsValue: undefined,
      deviceId: undefined,
      tableData: [],
      // 表单参数
      form: {},
      arrayOptions: [],
      objectData: {},
      open: false,
      title: '',
      result: {
        data: ''
      },
      // 表单校验
      rules: {},
      // 代码编辑器配置
      editorOptions: {
        // 设置代码编辑器的样式
        enableBasicAutocompletion: true, //启用基本自动完成
        enableSnippets: true, // 启用代码段
        enableLiveAutocompletion: true, //启用实时自动完成
        tabSize: 2, //标签大小
        fontSize: 14, //设置字号
        showPrintMargin: false //去除编辑器里的竖线
      }
    }
  },

  mounted() {
    // this.handleFormValidate()
  },

  methods: {
    handleSimpleModel(deviceId, functions) {
      this.deviceId = deviceId
      this.functions = functions
      this.tabsValue = functions[0] && functions[0].id
    },
    editorInit() {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/mode/json')    // language
      require('brace/theme/chrome')
      require('brace/snippets/json') // snippet
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.title = ''
    },
    handleClick(functions) {
      functions.forEach(fun => {
        this.$refs[`form${fun.id}`][0].clearValidate()
      })

    },
    change(row) {
      let type = row.valueType.type;
      let value = this.form[row.id];
      if (value === undefined) {
        return;
      }

      if (type === 'int' || type === 'long') {
        let flag = value.replace(/[^\d]/g, '');
        if (value !== flag) {
          this.$set(this.form, row.id, flag);
        }
        return eval("/[^\d]/g");
      } else if (type === 'float' || type === 'double') {
        let scale = row.valueType.scale;
        let regular = `/^\\d([0-9])*(\\.)?([0-9]){0,${scale}}$/`;
        //  /^\d([0-9])*(\.)?([0-9]){0,1}$/
        let flag = eval(regular).test(value);
        if (flag) {
          this.$set(this.form, row.id, value);
        } else {
          this.$set(this.form, row.id, value.slice(0, value.length - 1));
        }
        return eval(regular);
      }
    },
    handleRules(row) {
      let id = row.id;
      let valueType = row.valueType.type;

      this.rules[id] = [];
      this.rules[id].push(
        {required: true, message: row.name + '不能为空', trigger: ['blur', 'change']}
      )
      if (valueType === 'int' || valueType === 'long' || valueType === 'float' || valueType === 'double') {
        this.rules[id].push({pattern: this.change(row), message: '格式不正确', trigger: ['change', 'blur']})
      }
      if (valueType === 'object') {
        const jsonValidator = (rule, value, callback) => {
          try {
            JSON.parse(value)
          } catch (e) {
            callback(new Error('不是有效的JSON数据'))
            return
          }
          callback()
        }
        this.rules[id].push({required: true, validator: jsonValidator, trigger: ['change', 'blur']})
      }
      return this.rules[id];
    },
    handleInputs(data, id) {
      this.title = "编辑";
      this.open = true;
      this.objectData.params = data;
      this.objectData.id = id;
    },
    saveObject() {
      this.$set(this.form, this.objectData.id, this.objectData.params.replace(/<[^>]+>/g, ''));
      this.open = false;

    },

    // 表单重置
    reset(fun) {
      this.form = {}
      this.$refs[`form${fun.id}`][0].resetFields()
    },

    submitForm(fun) {
      this.$refs[`form${fun.id}`][0].validate(valid => {
        if (valid) {
          let data = {};
          fun.inputs.forEach(input => {
            let result = this.form.hasOwnProperty(input.id);
            if (result) {
              this.$set(data, input.id, this.form[input.id])
            }
          })

          invokedFunction(this.deviceId, fun.id, data).then(response => {
            if (typeof (response.data) === "object") {
              this.$set(this.result, 'data', JSON.stringify(response.data, null, 2));
            } else {
              this.$set(this.result, 'data', response.data);
            }

          })
        }
      })
    },

    handleFormShow(type, showTypes = []) {
      return !!showTypes.find(showType => showType === type);
    },

    handleFormValidate() {


      this.$set(this.rules, 'deviceName', {required: true, message: '请输入设备名称', trigger: 'change'})
    }
  }
}
</script>

<style lang="scss" scoped>

.el-form-item:last-child {
  margin-bottom: 0;
}

</style>
